<template>
  <a-modal title="模板管理" width="700px" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    />
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="downloadTemplate">导入模板</a-button>
        <a-button type="primary" @click="importTemplate">上传模板</a-button>
      </a-space>
    </template>
    <a-modal v-model:open="importTemplateShow" title="请输入模板名称" @ok="importSubmit" @cancel="importCancel">
      <a-textarea v-model:value="importTemplateValue" placeholder="模板名称" :rows="4" />
    </a-modal>
  </a-modal>
</template>

<script setup>
  import { reactive, ref, nextTick, defineProps } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { iotApi } from '/@/api/business/iotSystem/index.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { PageMixin } from '/@/utils/mixin';

  const { total, tableLoading, selectedRowKeyList, resetQueryForm, queryTableData, deleteFn, batchDeleteFn, queryFormState, watchTotal } =
    PageMixin();
  // ------------------------ 事件 ------------------------
  const emits = defineEmits(['reloadList', 'close']);

  const importTemplateShow = ref();
  const importTemplateValue = ref('');

  // 表格列
  const columns = ref([
    {
      title: '模板名称',
      dataIndex: 'name',
    },
  ]);

  const tableData = ref([]);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show() {
    visibleFlag.value = true;
    getList();
  }

  function getList() {
    iotApi.queryTemplateList().then(({ data }) => {
      tableData.value = data.map((m) => {
        return {
          id: m,
          name: m,
        };
      });
    });
  }

  function onClose() {
    selectedRowKeyList.value = [];
    visibleFlag.value = false;
    emits('close');
  }
  // ------------------------ 表单 ------------------------

  // 列选择
  function onSelectChange(selectedRowKeys) {
    if (selectedRowKeys.length > 1) {
      selectedRowKeyList.value = [selectedRowKeys[1]];
    } else {
      selectedRowKeyList.value = selectedRowKeys;
    }
  }

  // 点击确定，验证表单
  async function downloadTemplate() {
    try {
      if (selectedRowKeyList.value.length <= 0) {
        message.error('请选择至少一个模板!');
      } else {
        save(selectedRowKeyList.value);
      }
    } catch (err) {
      message.error('请选择至少一个模板!');
    }
  }

  // 新建、编辑API
  async function save(list) {
    try {
      SmartLoading.show(); // 显示加载动画
      const { data: taskId } = await iotApi.downloadTemplate({
        templateName: list[0],
      });

      const checkStatus = async () => {
        const { data: status } = await iotApi.getTaskStatus(taskId);
        if (status === 'COMPLETED') {
          message.success('导入成功！');
          return true;
        } else if (status === 'FAILED') {
          message.error('导入失败，请重试！');
          return true;
        }
        return false;
      };

      // 轮询检查任务状态
      const poll = async () => {
        let isDone = await checkStatus();
        if (!isDone) {
          setTimeout(poll, 2000); // 每 2 秒检查一次
        } else {
          SmartLoading.hide(); // 在任务完成时隐藏加载动画
          onClose(); // 关闭弹窗或完成其他清理逻辑
        }
      };

      await poll(); // 等待轮询结束
    } catch (err) {
      smartSentry.captureError(err); // 捕获错误日志
      SmartLoading.hide(); // 出现异常时隐藏加载动画
    }
  }

  function importTemplate() {
    importTemplateShow.value = true;
  }

  async function importSubmit() {
    if (!importTemplateValue.value) return;

    try {
      SmartLoading.show(); // 显示加载动画

      // 上传模板并获取任务 ID
      const { data: taskId } = await iotApi.uploadTemplate({
        fileName: importTemplateValue.value,
      });

      const checkStatus = async () => {
        const { data: status } = await iotApi.getTaskStatus(taskId);
        if (status === 'COMPLETED') {
          message.success('上传成功！');
          getList();
          return true;
        } else if (status === 'FAILED') {
          message.error('上传失败，请重试！');
          return true;
        }
        return false;
      };

      // 轮询检查任务状态
      const poll = async () => {
        let isDone = await checkStatus();
        if (!isDone) {
          setTimeout(poll, 2000); // 每 2 秒检查一次任务状态
        } else {
          SmartLoading.hide(); // 任务完成后隐藏加载动画
          importCancel(); // 关闭弹窗或执行其他清理逻辑
        }
      };

      await poll(); // 开始轮询
    } catch (err) {
      smartSentry.captureError(err); // 捕获错误日志
      message.error('上传失败，请重试！');
    } finally {
      SmartLoading.hide(); // 确保在任何情况下都隐藏加载动画
    }
  }

  function importCancel() {
    importTemplateShow.value = false;
    importTemplateValue.value = '';
  }

  defineExpose({
    show,
  });
</script>

<style scoped>
  .ant-select {
    width: 100% !important;
  }
</style>
